import { obj } from "../../index.js";
import dom, { ajax } from "../../init.js";
import { islogin } from "./user.js";

//更换头像
export default {
  async userImg(e: Event) {
    if (obj.islogin) {
      dom.user.imgipt.click();
    } else {
      if (dom.user.mubu.style.display == "none") {
        dom.user.mubu.style.display = "block";
      } else {
        if (e.target === dom.user.mubu) dom.user.mubu.style.display = "none";
      }
    }
  },
  async change() {
    let file = (dom.user.imgipt as any).files[0];
    const img = ["jpg", "jpeg", "png", "gif", "webs"];
    console.log("图片大小:", +(dom.user.imgipt as any).files[0].size / 1024);
    if (
      !img.includes(file.name.slice(file.name.indexOf(".") + 1)) ||
      (dom.user.imgipt as any).files[0].size / 1024 >= 200
    )
      return alert(
        `头像仅支持 'jpg', 'jpeg', 'png', 'gif', 'webs'\n且大小不能超过200kb `
      );
    const data = new FormData();
    data.append("file", file, file.name);
    const result = await ajax.post("/user/userimg", data as any);
    const info = JSON.parse(result as string);
    if (info.msg === "修改成功") {
      alert("修改成功");
      islogin();
    } else {
      alert("修改失败" + info.msg);
    }
  },
};
